package com.yc.Testjvm;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

public class LocalClassLoader extends ClassLoader {

    private String path = "F:/ws-test/";

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> cls = findLoadedClass(name);
        if (cls != null) {
            return cls;
        }

        if (!name.endsWith(".Key")) {
            return super.loadClass(name);
        }

        try {
            InputStream is = new FileInputStream(path + name.replace(".", "/") + ".class");
            byte[] bytes = IOUtils.toByteArray(is);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.loadClass(name);
    }
    
    public static void main(String[] args) {
        try {
            LocalClassLoader lcl = new LocalClassLoader();
            Class<?> cls = lcl.loadClass("com.test.jdk.Key");
            Field field = FieldUtils.getField(cls, "key", true);
            Object value = field.get(cls.newInstance());
            System.out.println(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
